import { SubjectComponent } from "../../../../core/subject";
import Utils, { Uid } from "../../../../core/utils";
import Bullet from "../../bullet";
import World from "../../world";
import BulletItem from "./bullet_item";

const { ccclass, property } = cc._decorator;

@ccclass
export default class BulletList extends SubjectComponent {
    @property(cc.Graphics)
    drawer: cc.Graphics = null;
    @property(cc.Node)
    contain: cc.Node = null;
    @property(cc.Prefab)
    bulletItemPrefab: cc.Prefab = null;
    world: World = null;
    items: BulletItem[] = [];

    hoveringItem: BulletItem = null;
    setData(world: World) {
        this.world = world;
        this.contain.destroyAllChildren();
        if (this.world) {
            this.world.bullets.forEach(bullet => {
                if (bullet.isCreateFromEditor) {
                    this.addItem(bullet);
                }
            });
        }
    }
    addItem(bullet: Bullet) {
        let item = cc.instantiate(this.bulletItemPrefab).getComponent(BulletItem);
        item.setData(bullet);
        this.contain.addChild(item.node);
        item.on("click", this.onClickItem, this);
        item.on("del", this.onClickItemDel, this);
        item.on("mouse-enter", this.onMouseEnter, this);
        item.on("mouse-leave", this.onMouseLeave, this);
        this.items.push(item);
    }
    delItem(bullet: Bullet) {
        let ind = this.items.findIndex(item => item.bullet == bullet);
        if (ind !== -1) {
            this.items.splice(ind, 1)[0].node.destroy();
        }
    }
    onMouseEnter(item: BulletItem) {
        this.hoveringItem = item;
    }
    onMouseLeave(item: BulletItem) {
        if (this.hoveringItem === item) {
            this.hoveringItem = null;
        }
    }
    onClickItem(item: BulletItem) {
        //移动画面
        this.emit("select-bullet", item.bullet);
    }
    onClickItemDel(item: BulletItem) {
        //删除bullet
        this.delItem(item.bullet);
        this.emit("delete-bullet", item.bullet);
    }

    protected lateUpdate(dt: number): void {
        this.drawer.clear();
        if (this.hoveringItem) {
            let np = this.drawer.node.convertToNodeSpaceAR(this.hoveringItem.node.convertToWorldSpaceAR(cc.Vec2.ZERO));

            this.drawer.moveTo(np.x, np.y);
            this.drawer.lineTo(np.x + 100, np.y);

            let bnp = this.convertBulletPosToUI(this.hoveringItem.bullet);
            this.drawer.lineTo(bnp.x, bnp.y);

            this.drawer.stroke();
        }
    }
    convertBulletPosToUI(bullet: Bullet) {
        let wp = bullet.world.node.convertToWorldSpaceAR(bullet.curPos);
        let cam = cc.Camera.findCamera(bullet.node);
        let wp3 = cc.v2(cam.getWorldToScreenPoint(wp));
        return this.drawer.node.convertToNodeSpaceAR(wp3);
    }
};